var async = require('async')
var util = require("../../../util/util.js")
var inviteCfg = require("../../../conf/invite.json")
var UUID = require("uuid");
module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
    DBRemote.channelService = this.app.get('channelService')
    if(DBRemote.dbService && DBRemote.dbService.db){
    	DBRemote.db = DBRemote.dbService.db
    }
}
var local = {}
//设置抽奖列表
DBRemote.prototype.setLotteryTable = function(data,cb) {
	//参数检测
	if(typeof(data) !== "object"){
		cb(false)
		return
	}
	var count = 0
	for(var i in data){
		if(	parseInt(i) < 0 ||	parseInt(i) > 9 ||
			typeof(data[i].itemId) != "number" || data[i].itemId < 0 ||
			typeof(data[i].itemName) != "string" ||
			typeof(data[i].title) != "string" ||
			typeof(data[i].count) != "number" || data[i].count < 0 ||
			typeof(data[i].weight) != "number" || data[i].weight < 0){
			console.log("参数错误")
			console.log(data)
			cb(false)
			return
		}
		count++
		data[i] = JSON.stringify(data[i])
	}
	if(count !== 10){
		cb(false)
		return
	}
	DBRemote.dbService.db.hmset("gameServer:lotteryTable",data,function(err,data) {
		if(err){
			console.log(err)
			cb(false)
		}else{
			cb(true)
		}
	})
}
//获取抽奖列表
DBRemote.prototype.getLotteryTable = function(cb) {
	DBRemote.dbService.db.hgetall("gameServer:lotteryTable",function(err,data) {
		for(var i in data){
			data[i] = JSON.parse(data[i])
		}
		cb(data)
	})
}
//获取库存表
DBRemote.prototype.getLotteryInventory = function(cb) {
	DBRemote.dbService.db.hgetall("gameServer:lotteryInventory",function(err,data) {
		for(var i in data){
			data[i] = parseInt(data[i])
		}
		cb(data)
	})
}
//设置库存表
DBRemote.prototype.setLotteryInventoryItem = function(data,cb) {
	//参数检测
	if(!data.itemId || typeof(data.value) !== "number" || data.value < 0){
		cb(false)
		return
	}
	DBRemote.dbService.db.hset("gameServer:lotteryInventory",data.itemId,data.value,function(err,data){
		if(err){
			console.log(err)
			cb(false)
		}else{
			cb(true)
		}
	})
}
//获取奖品列表
DBRemote.prototype.getLotteryAwardList = function(cb) {
	DBRemote.dbService.db.hgetall("gameServer:lotteryAwardList",function(err,data){
		for(var i in data){
			data[i] = JSON.parse(data[i])
		}
		cb(data)
	})
}
//设置奖品状态
DBRemote.prototype.sendAwardState = function(uid,orderNumber,state,cb) {
	if(typeof(state) !== "number"){
		cb(false)
		return
	}
	DBRemote.dbService.db.hget("gameServer:lotteryAwardList",uid,function(err,data){
		if(!err && data){
			data = JSON.parse(data)
			if(!data[orderNumber]){
				cb(false)
				return
			}
			data[orderNumber].state = state
			DBRemote.dbService.db.hset("gameServer:lotteryAwardList",uid,JSON.stringify(data),function() {
				cb(true)
			})
		}else{
			cb(false)
		}
	})
}
//获取单个玩家奖品背包
DBRemote.prototype.getLotteryAwardByUid = function(uid,cb) {
	DBRemote.dbService.db.hget("gameServer:lotteryAwardList",uid,function(err,data){
		if(err){
			cb({})
		}else{
			data = JSON.parse(data)
			cb(data)			
		}
	})
}
//获取抽奖记录
DBRemote.prototype.getLotteryHistory = function(cb) {
	DBRemote.dbService.db.lrange("gameServer:lotteryRecordList",-100,-1,function(err,data){
		for(var i in data){
			data[i] = JSON.parse(data[i])
		}
		cb(data)
	})
}
//获取抽奖次数
DBRemote.prototype.getLotteryCount = function(uid,cb) {
	DBRemote.dbService.db.hget("gameServer:lotteryCountList",uid,function(err,data) {
		if(!err && data && data > 0){
			cb(data)
		}else{
			cb(0)
		}
	})
}
//获取抽奖次数列表
DBRemote.prototype.getLotteryCountList = function(cb) {
	DBRemote.dbService.db.hgetall("gameServer:lotteryCountList",function(err,data) {
		if(!err && data){
			cb(data)
		}else{
			cb({})
		}
	})
}
//获取重要物品记录
DBRemote.prototype.getImportanceAwardList = function(cb) {
	DBRemote.dbService.db.lrange("gameServer:importanceAwardList",-20,-1,function(err,data) {
		if(!err && data){
			for(var i in data){
				data[i] = JSON.parse(data[i])
			}
			cb(data)
		}else{
			cb({})
		}
	})
}
//添加抽奖记录
DBRemote.prototype.addRobotLottery = function(index,cb) {
	if(typeof(index) !== "number" || index < 0 || index > 9){
		cb(false)
		return
	}
	DBRemote.prototype.getLotteryTable(function(data) {
		//抽中奖励
		var info = {
			"index" : index,
			"data" : data[index]
		}
		var id = (new Date()).valueOf() * 100000 + Math.floor(Math.random() * 100000)
		info.uid = Math.floor(Math.random() * 900)
		info.nickname = ""
		//重要物品记录
		info.time =  (new Date()).valueOf()
		if(info.data.importance && info.data.importance === true){
			DBRemote.dbService.db.rpush("gameServer:importanceAwardList",JSON.stringify(info))
			cb(true)
		}else{
			cb(false)
		}
	})
}
//抽奖
DBRemote.prototype.lottery = function(uid,cb) {
	var lotteryTable = {}
	var lotteryInventory = {}
	var nickname = ""
	async.waterfall([
			function(next) {
				//获取抽奖次数
				DBRemote.prototype.getLotteryCount(uid,function(data) {
					if(data > 0){
						next()
					}else{
						console.log("次数不足")
						cb(false)
					}
				})
			},
			function(next) {
				//获取玩家名字
				DBRemote.app.rpc.db.remote.getPlayerNickName(null,uid,function(data) {
					nickname = data
					next()
				})
			},
			function(next) {
				//获取抽奖表
				DBRemote.prototype.getLotteryTable(function(data) {
					lotteryTable = data
					// console.log("lotteryTable")
					// console.log(lotteryTable)
					next()
				})
			},
			function(next) {
				//获取抽奖库存
				DBRemote.prototype.getLotteryInventory(function(data) {
					lotteryInventory = data
					// console.log("lotteryInventory")
					// console.log(lotteryInventory)
					next()
				})
			},
			function(next) {
				//抽奖表根据库存调整，无库存的奖励设置权重为0
				var weightAll = 0
				for(var i in lotteryTable){
					if(lotteryTable[i].itemId !== 0 && lotteryTable[i].itemId !== 101 && lotteryTable[i].itemId !== 102 && (!lotteryInventory[lotteryTable[i].itemId] || lotteryInventory[lotteryTable[i].itemId] <= 0)){
						lotteryTable[i].weight = 0
					}
					weightAll += lotteryTable[i].weight
				}
				//获取奖励
				var tmpRand = Math.random() * weightAll
				var weightCur = 0
				for(var i in lotteryTable){
					if(tmpRand >= weightCur && tmpRand < lotteryTable[i].weight + weightCur){
						//扣除次数
						DBRemote.prototype.addLotteryCount(uid,-1)
						//抽中奖励
						var info = {
							"index" : i,
							"data" : lotteryTable[i]
						}
						cb(info)
						//抽奖记录
						var id = (new Date()).valueOf() * 100000 + Math.floor(Math.random() * 100000)
						info.uid = uid
						info.nickname = nickname
						info.id = id
						DBRemote.dbService.db.rpush("gameServer:lotteryRecordList",JSON.stringify(info))
						//重要物品记录
						info.time =  (new Date()).valueOf()
						if(info.data.importance && info.data.importance === true){
							DBRemote.dbService.db.rpush("gameServer:importanceAwardList",JSON.stringify(info))
						}
						if(!lotteryTable[i].count || typeof(lotteryTable[i].count) !== "number"){
							lotteryTable[i].count = 0
						}
						switch(lotteryTable[i].itemId){
							case 0 :
								//不处理
							break
							case 101:
								//获得房卡
								DBRemote.dbService.addItemReason(uid,101,lotteryTable[i].count,"抽奖",function(){})
							break
							case 102:
								//获得金币
								DBRemote.dbService.addItemReason(uid,102,lotteryTable[i].count,"抽奖",function(){})
							break
							default :
								//获得物品  降低库存
								DBRemote.dbService.db.hincrby("gameServer:lotteryInventory",lotteryTable[i].itemId,-lotteryTable[i].count,function(err) {})
								DBRemote.dbService.addItemReason(uid,lotteryTable[i].itemId,lotteryTable[i].count,"抽奖",function(err,data){})
							break
						}
						return
					}else{
						weightCur += lotteryTable[i].weight
					}
				}
				cb(false)
				return
			}
		],function(err,data) {
		console.log(err)
		console.log(data)
	})
}
//抽奖次数增加
DBRemote.prototype.addLotteryCount = function(uid,count,cb) {
	DBRemote.dbService.addItem(uid,201,count,cb)
}
//领取签到奖励
DBRemote.prototype.getLoginAward = function(uid,cb) {
	local.getLoginInfo(uid,function(flag,data) {
		var curDate = (new Date()).toDateString()
		if(flag){
			data = JSON.parse(data)
			data.days = parseInt(data.days)
			var count = util.dayCompare(curDate,data.lastTime)
			// console.log("count : "+count)
			if(count <= 0){
				cb(false,"今日已领取")
			}else if(count > 1 || data.days >= 2){
				//连续登陆失效，重新获取
				local.getLoginAward(uid,0,curDate,cb)
			}else{
				//获取连续登陆奖励
				local.getLoginAward(uid,data.days + 1,curDate,cb)
			}
		}else{
			local.getLoginAward(uid,0,curDate,cb)
		}
	})
}
//获取连续登陆信息
DBRemote.prototype.getLoginInfo = function(uid,cb) {
	local.getLoginInfo(uid,cb)
}
//获取邀请信息
DBRemote.prototype.getInviteInfo = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:inviteInfo:"+uid,function(err,data) {
		if(err || !data){
			cb(true,{})
		}else{
			cb(true,data)
		}
	})
}
//领取邀请奖励
DBRemote.prototype.getInviteAward = function(uid,boxId,cb) {
	DBRemote.dbService.db.hdel("game:inviteInfo:"+uid,"award:"+boxId,function(err,data) {
		if(err || !data){
			cb(false)
		}else{
			if(inviteCfg[boxId]){
				var itemId = parseInt(inviteCfg[boxId].split(":")[0])
				var value = parseInt(inviteCfg[boxId].split(":")[1])
				DBRemote.app.rpc.db.remote.addItemReason(null,uid,itemId,value,"邀请宝箱:"+boxId,function(){})
				cb(true,{itemId : itemId,value : value})
			}else{
				cb(false)
			}
		}
	})
}
local.getLoginInfo = function(uid,cb) {
	DBRemote.dbService.db.hget("gameServer:successionLoginInfo",uid,function(err,data) {
		if(!err && data){
			cb(true,data)
		}else{
			cb(false)
		}
	})
}
local.getLoginAward = function(uid,days,lastTime,cb) {
	var info = {
		days : days,
		lastTime : lastTime
	}
	DBRemote.dbService.db.hset("gameServer:successionLoginInfo",uid,JSON.stringify(info),function(err) {
		if(!err){
			DBRemote.dbService.db.hget("gameServer:successionLoginAward",days,function(err,data) {
				// console.log(err)
				// console.log(data)
				if(!err && data){
					data = JSON.parse(data)
					for(var i in data){
						data[i] = parseInt(data[i])
					}
					DBRemote.app.rpc.db.remote.addItemReason(null,uid,data.itemId,data.count,"签到",function(){})
					cb(true,data)
				}else{
					cb(false)
				}
			})
		}else{
			cb(false)
		}
	})
}
//获取登录奖励信息
DBRemote.prototype.getAppLoginInfo = function(uid,cb) {
	DBRemote.dbService.db.hget("gameServer:AppLoginAward",uid,function(err,data){
		if(err || !data){
			cb(true,0)
		}else{
			cb(true,data)
		}
	})
}
//领取奖励
DBRemote.prototype.getAppLoginAward = function(uid,cb) {
	DBRemote.dbService.db.hincrby("gameServer:AppLoginAward",uid,1,function(err,data){
		if(err || !data){
			cb(false)
		}else{
			if(data == 1){
				var value = parseFloat((Math.random() * 0.5 + 0.5).toFixed(2))
				DBRemote.app.rpc.db.mail.sendMail(null,uid,"APP登录奖励","恭喜您获得APP首次登录奖励",{"103" : value},null)
				cb(true,{"103" : value})
			}else{
				cb(false)
			}
		}
	})
}
//获取新手七日奖信息
DBRemote.prototype.getNewPlayerRedInfo = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:newPlayerRed:"+uid,function(err,data) {
		if(!err && data){
			cb(true,data)
		}else{
			cb(false)
		}
	})
}
//领取每日新手七日奖
DBRemote.prototype.getNewPlayerRedDay = function(uid,cb) {
	var curDate = util.getDateString()
	DBRemote.dbService.db.hgetall("game:newPlayerRed:"+uid,function(err,data) {
		if(!err && data && data[curDate] == "none"){
			var value = ((10 - parseInt(data["allValue"])) * (Math.random() * 0.1 + 0.2)).toFixed(2)
			DBRemote.dbService.db.hset("game:newPlayerRed:"+uid,curDate,value)
			DBRemote.dbService.db.hincrbyfloat("game:newPlayerRed:"+uid,"allValue",parseFloat(value))
			cb(true,{"value" : value})
		}else{
			cb(false)
		}
	})
}
//领取新手七日奖最终红包
DBRemote.prototype.getNewPlayerRedAward = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:newPlayerRed:"+uid,function(err,data) {
		if(!err && data && !data["over"]){
			DBRemote.dbService.addItemReason(uid,101,10,"新手七日奖",function(){})
			DBRemote.dbService.db.hset("game:newPlayerRed:"+uid,"over",true)
			cb(true)
		}else{
			cb(false)
		}
	})
}

//==============================发货系统============================//

//设置收货地址
DBRemote.prototype.setAddress = function(uid,address,index,cb){
	if(typeof(index) != "number" || index < 0 || index > 10 || parseInt(index) != index){
		cb(false,"index error : "+index)
		return
	}
	DBRemote.dbService.db.hset("game:address:"+uid,index,address,function(err,data) {
		if(err){
			cb(false,err)
		}else{
			cb(true)
		}
	})
}
//获取收货地址
DBRemote.prototype.getAddress = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:address:"+uid,function(err,data) {
		if(err || !data){
			cb(true,{})
		}else{
			cb(true,data)
		}
	})
}
//玩家申请发货
DBRemote.prototype.applyDelivery = function(uid,itemId,index,cb) {
	var address = ""
	async.waterfall([
		function(next) {
			//获取收货地址
			DBRemote.dbService.db.hget("game:address:"+uid,index,function(err,data) {
				if(err || !data){
					cb(false,"收货地址错误")
				}else{
					address = data
					next()
				}
			})
		},
		function(next) {
			//检测背包
			DBRemote.dbService.getItem(uid,itemId,function(data) {
				console.log("data : ",data)
				if(data >= 1){
					DBRemote.dbService.addItemReason(uid,itemId,-1,"申请发货扣除",function(data) {
						if(data >= 0){
							next()
						}else{
							DBRemote.dbService.addItemReason(uid,itemId,1,"申请发货失败")
							cb(false,"请勿重复申请")
						}
					})
				}else{
					cb(false,"物品不足")
				}
			})
		},
		function() {
			//写入发货列表
			var deliveryId = UUID.v1()
			var info = {
				deliveryId : deliveryId,
				uid : uid,
				applyTime : (new Date()).getTime(),
				address : address,
				itemId : itemId
			}
			var infoStr = JSON.stringify(info)
			DBRemote.dbService.db.hset("game:allWaitDeliverys",deliveryId,infoStr,function(err,data) {
				if(err){
					cb(false,err)
				}else{
					DBRemote.dbService.db.hset("game:userWaitDeliverys:"+uid,deliveryId,infoStr)
					cb(true,info)
				}
			})
		}
	],function(err) {
		cb(false,err)
	})
}
//玩家获取待发货列表
DBRemote.prototype.getUserWaitDeliverys = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:userWaitDeliverys:"+uid,function(err,data) {
		if(err || !data){
			cb(true,{})
		}else{
			cb(true,data)
		}
	})
}
//玩家获取已发货列表
DBRemote.prototype.getUserFinishDeliverys = function(uid,begin,cb) {
	DBRemote.dbService.getList("game:userFinishDeliverys:"+uid,begin,10,cb)
}
//管理员获取待发货列表
DBRemote.prototype.getAllWaitDeliverys = function(cb) {
	DBRemote.dbService.db.hgetall("game:allWaitDeliverys",function(err,data) {
		if(err || !data){
			cb(true,{})
		}else{
			cb(true,data)
		}
	})
}
//管理员获取已发货列表
DBRemote.prototype.getAllFinishDeliverys = function(begin,cb) {
	DBRemote.dbService.getList("game:allFinishDeliverys",begin,10,cb)
}
//管理员确认发货
DBRemote.prototype.submitDeliverys = function(deliveryId,LogisticCode,cb) {
	var info = {}
	async.waterfall([
		function(next) {
			//获取记录
			DBRemote.dbService.db.hget("game:allWaitDeliverys",deliveryId,function(err,data) {
				if(err || !data){
					cb(false,"deliveryId error : "+deliveryId)
					return
				}
				info = JSON.parse(data)
				info.finishTime = (new Date()).getTime()
				info.LogisticCode = LogisticCode
				info.state = true
				next()
			})
		},
		function(next) {
			var infoStr = JSON.stringify(info)
			DBRemote.dbService.db.hdel("game:allWaitDeliverys",deliveryId)
			DBRemote.dbService.db.hdel("game:userWaitDeliverys:"+info.uid,deliveryId)
			DBRemote.dbService.db.rpush("game:userFinishDeliverys:"+info.uid,infoStr)
			DBRemote.dbService.db.rpush("game:allFinishDeliverys",infoStr)
			cb(true)
		}
	],function(err) {
		console.log(err)
		cb(false,err)
	})
}
//管理员拒绝发货申请
DBRemote.prototype.rejectDeliverys = function(deliveryId,reason,cb) {
	//获取记录
	DBRemote.dbService.db.hget("game:allWaitDeliverys",deliveryId,function(err,data) {
		if(err || !data){
			cb(false,"deliveryId error : "+deliveryId)
			return
		}
		var info = JSON.parse(data)
		info.state = false
		info.reason = reason || "管理员拒绝发货"
		var infoStr = JSON.stringify(info)
		DBRemote.dbService.db.hdel("game:allWaitDeliverys",deliveryId)
		DBRemote.dbService.db.hdel("game:userWaitDeliverys:"+info.uid,deliveryId)
		DBRemote.dbService.addItemReason(info.uid,info.itemId,1,"管理员拒绝发货")
		DBRemote.dbService.db.rpush("game:userFinishDeliverys:"+info.uid,infoStr)
		cb(true)
	})
}

